<!-- eslint-disable vue/order-in-components -->
<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <el-button v-if="hasPointsPermission('excel_import')" type="warning" size="small" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button v-if="hasPointsPermission('excel_export')" type="danger" size="small" @click="exportExcel">excel导出</el-button>
          <el-button v-if="hasPointsPermission('p-em-add')" type="primary" size="small" @click="addEmployeeFn">新增员工</el-button>
        </template>
      </page-tools>

      <el-card v-loading="isLoading" style="margin-top: 10px;">
        <el-table border :data="employeeList">
          <el-table-column label="序号" width="80" type="index" :index="indexMethod" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template #default="{row}">
              <img v-imgerror="defaultImg" :src="row.staffPhoto||nullImage" class="imgStyle">
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formateData" />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry">
            <template #default="{row}">
              {{ formatTime(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{row}">
              <el-button v-if="hasPointsPermission('p-em-look')" type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button v-if="hasPointsPermission('assign_role')" type="text" size="small" @click="assignRoleClick(row.id)">分配角色</el-button>
              <el-button v-if="hasPointsPermission('emp_delete')" type="text" size="small" @click="del(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <!-- current-page 表示的当前是那一页 -->
        <!-- page-sizes 动态设置页容量的下拉列表 -->
        <!-- page-size 表示当前的页容量 -->
        <!-- layout 表示的分页样式 -->
        <!-- total 表示的 一共有多少条 -->
        <!-- @current-change 表示的点击页码的时候执行的事件-->
        <!-- @size-change 表示的动态设置页容量的时候执行的事件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :current-page="page"
            :page-size="size"
            :page-sizes="[4, 5, 10]"
            layout="total,sizes,prev, pager, next,jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
        <addEmployees :show-dialog.sync="showDialog" />
      </el-card>
      <assignRole
        :show-role-dialog.sync="showRoleDialog"
        :user-id="userId"
      />
    </div>
  </div>
</template>

<script>
import { getEmployeesListApi, delEmployeesListApi } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import dayjs from 'dayjs'
import addEmployees from './components/addEmployees.vue'
import avatar from '@/assets/common/bigUserHeader.png'
import assignRole from './components/assign-role.vue'
import { mapGetters } from 'vuex'
export default {
  name: 'Employees',
  components: {
    addEmployees,
    assignRole
  },
  data() {
    return {
      page: 1, // 当前页
      size: 4, // 每页多少条
      total: 0, // 总条数
      employeeList: [],
      isLoading: false,
      showDialog: false,
      defaultImg: avatar,
      nullImage:
        'http://heimamianjing-1315206099.cos.ap-beijing.myqcloud.com/1669080961265%E8%87%AD%E5%AE%9D.jpg',
      showRoleDialog: false,
      userId: ''
    }
  },
  computed: {
    ...mapGetters(['roles'])
  },
  created() {
    this.getEmployeesList()
  },
  methods: {
    hasPointsPermission(points) {
      // console.log(this.roles.points)
      return this.roles?.points.includes(points)
    },
    assignRoleClick(id) {
      this.showRoleDialog = true
      this.userId = id
    },
    async exportExcel() {
      // 请注意: 如果导出的是当前页, 那么数据, this.list 即可,
      // 但是我们一般导出的是全部的数据, 需要请求到所有的数据
      const headersArr = [
        '姓名',
        '手机号',
        '入职日期',
        '聘用形式',
        '转正日期',
        '工号',
        '部门'
      ]
      const {
        data: { rows }
      } = await getEmployeesListApi(1, this.total)
      const headersRelations = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      const data = this.formateData2Array(headersArr, rows, headersRelations)
      import('@/vendor/Export2Excel').then((excel) => {
        excel.export_json_to_excel({
          header: headersArr,
          // 导出的数据必须是二维数组
          data: data,
          filename: '员工信息', // 导出文件的文件名
          autoWidth: true, // 单元格宽度是否自适应
          bookType: 'xlsx' // 文件的后缀名
        })
      })
    },

    // 将表头数据和数据进行对应
    formateData2Array(headersArr, rows, headersRelations) {
      const arr = []
      rows.forEach((item) => {
        const tempArray = []
        headersArr.forEach((key) => {
          const englishKey = headersRelations[key]
          let value = item[englishKey]
          if (englishKey === 'formOfEmployment') {
            const hireObj = EmployeeEnum.hireType.find(
              (item) => item.id === Number(value)
            )
            value = hireObj ? hireObj.value : '未知'
          }
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            value = value ? this.formatTime(value) : ''
          }
          tempArray.push(value)
        })
        arr.push(tempArray)
      })
      return arr
    },
    addEmployeeFn() {
      this.showDialog = true
    },
    formateData(row, column, cellValue, index) {
      // console.log(row)
      // console.log(column)
      // console.log(cellValue)
      // console.log(index)
      // const hireObj = EmployeeEnum.hireType.find(item => {
      //   if (item.id === cellValue) {
      //     console.log(1)
      //     return hireObj ? hireObj.value : '未知'
      //   }
      // })
      const hireObj = EmployeeEnum.hireType.find(item => item.id === +cellValue)
      // console.log(typeof (cellValue))
      return hireObj ? hireObj.value : '未知'
    },
    formatTime(time) {
      return dayjs(time).format('YYYY-MM-DD')
    },
    async getEmployeesList() {
      this.isLoading = true
      const { data } = await getEmployeesListApi(this.page, this.size)
      // console.log(data)
      this.employeeList = data.rows
      this.total = data.total
      this.isLoading = false
    },
    // 改变页容量
    handleSizeChange(val) {
      this.size = val
      this.getEmployeesList()
    },
    // 页码改变
    handleCurrentChange(val) {
      this.page = val
      this.getEmployeesList()
    },
    indexMethod(index) {
      return (this.page - 1) * this.size + index + 1
    },
    // 删除员工
    del(id) {
      this.$confirm('你确认要进行删除么?', '温馨提示').then(async() => {
        // 删除操作成功
        await delEmployeesListApi(id)
        if (this.employeeList.length === 1 && this.page > 1) {
          this.page--
        }
        // 添加提示
        this.$message.success('删除角色成功')
        this.getEmployeesList()
      }).catch((error) => { console.log(error) })
    }
  }
}
</script>

<style lang="scss" scoped>
.imgStyle{
width: 70px;
height: 70px;
}
</style>
